<template>
  <Modal v-model="modalFirst" id="ModalFirst" :styles="{ top: '50px' }">
    <p slot="header" class="modal_head">
      <span v-show="modalTitle != 4">{{
        modalTitle == 0
          ? "创建聊天"
          : modalTitle == 1
          ? "发送广播"
          : modalTitle == 2
          ? "转发消息"
          : "转发文件"
      }}</span>
      <span v-show="modalTitle == 4">添加成员</span>
    </p>
    <div class="modal_main">
      <div class="modal_left_w">
        <div class="modal_l_btn_w">
          <div class="m_l_btn_m">
            <Button class="my_btn">{{ myInfo.name }}</Button>
            <Button
              class="ot_btn"
              v-for="(item, index) in checkPersonArray"
              :key="index"
            >
              <span>{{ item.name }}</span>
              <span
                class="modalPersonButtonClose"
                @click="checkPersonDelete(item, index)"
              ></span>
            </Button>
          </div>
        </div>
        <div v-show="modalTitle == 0">
          <div>群名称 <span class="group_n_t">-选填</span></div>
          <input
            type="text"
            placeholder="取个群名称方便后续搜索"
            class="homeModalName"
            v-model="modalNameValue"
          />
        </div>
        <div class="modal_b_w">
          <Button type="info" @click.native="determine" class="determine_btn"
            >确定({{ personCount }}/1000)</Button
          >
          <Button @click="modalFirst = false">取消</Button>
        </div>
      </div>
      <div class="modal_right_w">
        <div class="modal_search_box">
          <input
            class="moadl_s_val"
            type="text"
            placeholder="搜索名字、手机号"
            v-model="modalSearchValue"
          />
          <ul
            class="modalSearchResultUlStyle"
            v-show="modalSearchResult != null && modalSearchResult.length > 0"
          >
            <li
              class="modalSearchList"
              v-for="(item, index) in modalSearchResult"
              @click="setStruChoose(item, index)"
              :key="index"
            >
              {{ item.name }}&nbsp;{{ item.departmentname }}
            </li>
          </ul>
        </div>
        <ul class="homeContact" v-if="modalCheckArray.show == false">
          <li
            v-for="(item, index) in modalFirstList"
            :key="index"
            @click="setModalCheckArray(item, index)"
            v-show="
              modalTitle == 2 ||
              (modalTitle == 1 && item.id == 3) ||
              (modalTitle == 0 && item.id != 5) ||
              (modalTitle == 4 && item.id != 5)
            "
          >
            <img draggable="false" :src="item.url" />
            <span>{{ item.title }}</span>
          </li>
        </ul>
        <div v-if="modalCheckArray.show != false" class="modal_arr_box">
          <div class="modal_r_s_t">
            <span class="modalBack" @click="setModalCheckArray(null)"></span>
            <h3>按{{ modalCheckArray.title }}查找</h3>
          </div>
          <div v-if="modalCheckArray.id == 4" class="modal_firend_box">
            <ul>
              <li v-for="(item, index) in modalCheckArray.list" :key="index">
                <ul>
                  <li
                    v-for="(temp, count) in item"
                    class="modalFirendList"
                    @click="setChoose(temp, count)"
                    :key="count"
                  >
                    <span
                      class="checkSpan"
                      :class="{ chooseSpan: temp.isChoose }"
                    ></span>
                    <img
                      v-if="temp.gender == 1"
                      draggable="false"
                      src="static/image/home/person_1.png"
                      class="person_img"
                    />
                    <img
                      v-else
                      draggable="false"
                      src="static/image/home/person_2.png"
                      class="person_img"
                    />
                    <span>{{ temp.name }}</span>
                  </li>
                </ul>
              </li>
            </ul>
          </div>
          <div v-if="modalCheckArray.id == 5" class="modal_firend_box">
            <ul>
              <li
                v-for="(temp, count) in modalCheckArray.list3"
                class="modalFirendList"
                @click="setLastChoose(temp, count)"
                :key="count"
              >
                <span
                  class="checkSpan"
                  :class="{ chooseSpan: temp.isChoose }"
                ></span>
                <img
                  v-if="temp.gender == 1"
                  draggable="false"
                  src="static/image/home/person_1.png"
                  class="person_img"
                />
                <img
                  v-else
                  draggable="false"
                  src="static/image/home/person_2.png"
                  class="person_img"
                />
                <span>{{ temp.name }}</span>
              </li>
            </ul>
          </div>
          <div v-if="modalCheckArray.id == 3" class="modal_nav_box">
            <div class="modal_nav">
              <div
                class="modal_nav_item"
                v-for="(item, index) in modalCheckArray.navList"
                :key="index"
              >
                <span v-if="index != 0" class="m_v_i_f">/</span>
                <span
                  class="navTitle"
                  v-if="index != modalCheckArray.navList.length - 1"
                  @click="setModalIndex(item, index)"
                  >{{ item.value }}</span
                >
                <span v-else class="m_n_v">{{ item.value }}</span>
              </div>
            </div>
            <ul class="modal_stru_box">
              <li
                v-for="(item, index) in modalCheckArray.list2[
                  this.modalCheckArray.index
                ]"
                class="modalFirendList"
                @click="modalGetStru(item, index)"
                :key="index"
              >
                <span
                  class="checkSpan"
                  :class="{ chooseSpan: item.isChoose || item.NO == myInfo.id }"
                  @click.stop="setStruChoose(item, index)"
                ></span>
                <img
                  draggable="false"
                  :src="
                    item.FID
                      ? 'static/image/home/contact/next.png'
                      : `static/image/home/person_${
                          (item.SEX || item.GENDER || item.gender) == 1 ? 1 : 2
                        }.png`
                  "
                  class="stru_icon"
                  :class="{ fidNextImg: item.FID }"
                />
                <span>{{ item.LEABLE }}</span>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </Modal>
</template>

<script>
import { getUserList, getGroup, addGroup } from "@/api/publicModal";
export default {
  name: "modal-first",
  props: {
    forwarding_array: {
      type: Object,
      default: {}
    },
    friendsList: {
      type: Array,
      default: []
    },
    personalStatus: {
      type: Number,
      default: 0
    },
    modalFirst: {
      type: Boolean,
      default: false
    },
    modalTitle: {
      type: Number,
      default: 0
    }
  },
  watch: {
    checkPersonArray() {
      let count = 0;
      for (let i = 0; i < this.checkPersonArray.length; i++) {
        if (this.checkPersonArray[i].CN) {
          count += parseInt(this.checkPersonArray[i].CN) || 0;
        } else {
          count += 1;
        }
      }
      this.personCount = count;
    },
    modalFirst() {
      if (this.modalFirst == false) {
        this.modalSearchValue = this.modalNameValue = "";
      }
    },
    modalSearchValue() {
      if (this.modalSearchValue != "") {
        getUserList({
          userid: this.myInfo.id,
          name: this.modalSearchValue,
          pageSize: "1000",
          pageNumber: 1
        }).then(res => {
          console.log(res, "搜索结果");
          let result = res.data;
          //过滤已选ID
          result = result.filter(
            item => !this.checkPersonArray.some(ele => ele.id === item.id)
          );
          this.modalSearchResult = result;
          console.log(this.modalSearchResult);
        });
      } else {
        this.modalSearchResult = [];
        this.searchResultShow = false;
      }
    }
  },
  data() {
    return {
      personCount: 0,
      modalSearchResult: [],
      modalCheckArray: {
        show: false
      }, //modal已选择数组
      checkPersonArray: [],
      modalFirstList: [
        {
          id: 4,
          title: "常用联系人",
          url: "static/image/home/contact/contact.png",
          show: true
        },
        {
          id: 3,
          title: "组织架构",
          url: "static/image/home/contact/structure.png",
          show: true,
          structureShow: false,
          structureList: []
        },
        {
          id: 5,
          title: "最近联系人",
          url: "static/image/home/contact/contact.png",
          show: true
        }
      ], //创建聊天右侧
      modalSearchValue: "", //创建聊天搜索值
      modalNameValue: "" //创建聊天名字
    };
  },
  computed: {
    ...mapState(["myInfo"])
  },
  methods: {
    //组织架构树状点击打开|选择
    modalGetStru(item, index) {
      if (item.FID) {
        if (item.isChoose) return;
        this.modalCheckArray.index = item.FID;
        if (this.modalCheckArray.list2[this.modalCheckArray.index]) {
          this.modalCheckArray.navList.push({
            title: item.FID,
            value: item.LEABLE
          });
        } else {
          getGroup({ fid: item.FID }).then(res => {
            console.log(res, "组织架构public");
            let result = res.data;
            for (let i = 0; i < this.checkPersonArray.length; i++) {
              for (let j = 0; j < result.length; j++) {
                if (result[j].NO == this.checkPersonArray[i].id)
                  this.$set(result[j], "isChoose", true);
              }
            }
            this.modalCheckArray.list2[item.FID] = result;
            this.modalCheckArray.navList.push({
              title: item.FID,
              value: item.LEABLE
            });
            this.$forceUpdate();
          });
        }
        console.log(item, "组织架构树状点击打开");
      } else {
        this.setStruChoose(item, index);
      }
    },
    //最近联系人选择成员
    setLastChoose(item, index) {
      let res = !item.isChoose;
      this.$set(item, "isChoose", res);
      if (res) {
        this.checkPersonArray.push(item);
      } else {
        this.delCheckPerson(item.id);
      }
      console.log(item, "最近联系人选择成员");
      this.setInitChoose(item.id, res);
    },
    //组织架构选择成员
    setStruChoose(item, index) {
      if (
        item.NO == this.myInfo.id ||
        item.id == this.myInfo.id ||
        item.FID == this.myInfo.id
      ) {
        this.$Message.destroy();
        this.$Message.warning({
          content: "不能选择自己",
          duration: 0.8
        });
        return;
      }
      console.log(item, "组织架构选择成员");
      let result = !item.isChoose;
      this.$set(item, "isChoose", result);
      if (result) {
        if (item.CN) {
          if (this.personCount + (parseInt(item.CN) || 0) > 1000) {
            this.$set(item, "isChoose", !result);
            this.$Message.warning({
              content: "选择将超过最大人数",
              duration: 0.8
            });
            return;
          }
        } else {
          if (this.personCount + 1 > 1000) {
            this.$set(item, "isChoose", !result);
            this.$Message.warning({
              content: "选择将超过最大人数",
              duration: 0.8
            });
            return;
          }
        }
        item.id = item.NO || item.FID || item.id;
        item.name = item.LEABLE || item.name;
        this.checkPersonArray.push(item);
      } else {
        this.delCheckPerson(item.NO || item.FID || item.id);
      }
      this.setInitChoose(item.NO || item.FID || item.id, result);
      this.modalSearchValue = "";
      this.$forceUpdate();
    },
    //建群、发送广播、转发左侧列表删除成员
    checkPersonDelete(item, index) {
      this.setInitChoose(item.id, false);
      this.checkPersonArray.splice(index, 1);
    },
    //移出人员
    delCheckPerson(id) {
      for (let i = 0; i < this.checkPersonArray.length; i++) {
        this.checkPersonArray[i].id == id && this.checkPersonArray.splice(i, 1);
      }
    },
    //设置选中|取消 id、数组、结果
    setInitChoose(id, result) {
      let at = ["list", "list2", "list3"];
      for (let n in at) {
        let another = at[n];
        let tag = at[n] == "list2" ? "NO" : "id";
        for (let i in this.modalCheckArray[another]) {
          let arr = this.modalCheckArray[another][i];
          for (let j in arr) {
            if (arr[j][tag] == id || (tag == "NO" && arr[j].FID == id))
              this.$set(
                this.modalCheckArray[another][i][j],
                "isChoose",
                result
              );
          }
        }
      }
    },
    //建群、发送广播、转发右侧父列表事件
    setModalCheckArray(item, index) {
      let itemBool = item != null;
      this.$set(this.modalCheckArray, "show", itemBool);
      if (itemBool) {
        this.$set(this.modalCheckArray, "show", true);
        this.$set(this.modalCheckArray, "title", item.title);
        this.$set(this.modalCheckArray, "id", item.id);
        this.$set(this.modalCheckArray, "index", "all");
        this.$set(this.modalCheckArray, "navList", [
          {
            title: "all",
            value: "组织架构"
          }
        ]);
        if (item.id == 4 && !this.modalCheckArray.list) {
          Object.assign(this.modalCheckArray, {
            list: this.friendsList
          });
          console.log(this.modalCheckArray.list, "联系人");
          console.log(this.friendsList, "联系人1");
          for (let i in this.checkPersonArray) {
            this.setInitChoose(this.checkPersonArray[i].id, true);
          }
        } else if (item.id == 3 && !this.modalCheckArray.list2) {
          Object.assign(this.modalCheckArray, {
            list2: {
              all: this.$store.state.tree.list
            },
            index: "all"
          });
        } else if (item.id == 5 && !this.modalCheckArray.list3) {
          let res = this.init_session_list();
          Object.assign(this.modalCheckArray, {
            list3: res
          });
          for (let i in this.checkPersonArray) {
            this.setInitChoose(this.checkPersonArray[i].id, true);
          }
        }
      }
    },
    //常用联系人选择成员
    setChoose(item, index) {
      let result = !item.isChoose;
      this.$set(item, "isChoose", result);
      if (result) {
        this.checkPersonArray.push(item);
      } else {
        this.delCheckPerson(item.id);
      }
      this.setInitChoose(item.id, result);
      console.log(item, "常用联系人选择成员");
    },
    //建群
    determine() {
      if (this.personalStatus == 4) {
        this.$Message.warning("离线状态无进行该操作");
        return;
      }
      let arr = [];
      if (this.modalTitle == 0) {
        for (let i = 0, len = this.checkPersonArray.length; i < len; i++) {
          arr.push({
            type: this.checkPersonArray[i].FID ? "1" : "0",
            value: this.checkPersonArray[i].id
          });
        }
        let groupName =
          this.modalNameValue.trim() == ""
            ? "群聊"
            : this.modalNameValue.trim();
        if (arr.length > 0) {
          addGroup({
            userid: this.myInfo.id,
            name: groupName,
            introduce: "",
            members: JSON.stringify(arr)
          }).then(res => {
            if (res.result == 200) {
              this.resetModalFirst();
              // this.resetContacts();
              this.modalFirst = false;
              this.$Message.success("创建成功");
            } else if (res.result == 4) {
              this.$Message.warning("系统错误");
            } else if (res.result == 2) {
              this.$Message.warning("无权限");
            }
          });
        } else {
          this.$Message.destroy();
          this.$Message.warning({
            content: "至少邀请1位联系人加入群",
            duration: 1
          });
        }
      } else if (this.modalTitle == 1) {
        for (let i in this.checkPersonArray) {
          arr.push({
            type: this.checkPersonArray[i].FID ? "1" : "0",
            id: this.checkPersonArray[i].id,
            value: this.checkPersonArray[i].id,
            name: this.checkPersonArray[i].name
          });
        }
        this.broadSendList = arr;
        this.modalFirst = false;
        this.resetContacts();
      } else if (this.modalTitle == 2) {
        for (let i in this.checkPersonArray) {
          this.checkPersonArray[i].isGroup =
            this.checkPersonArray[i].isGroup == "1" ? "1" : "0";
          let initKey = this.$func.uuid();
          console.log(this.forwarding_array, "转发");
          if (this.forwarding_array.type == "image") {
            this.$wsSendMsg(
              this.checkPersonArray[i],
              initKey,
              this.forwarding_array.type,
              {
                id: this.forwarding_array.DownLoadId,
                size: this.forwarding_array.duration,
                name: this.myInfo.id + new Date().getTime() + ".jpg",
                duration: 32,
                gender: this.checkPersonArray[i].gender || "1",
                head: this.checkPersonArray[i].head || ""
              },
              this.ws
            );
          } else if (this.forwarding_array.type == "file") {
            if (this.checkPersonArray[i].uploading) {
              this.$Message.success("文件上传中,请稍后转发");
              return;
            }
            this.$wsSendMsg(
              this.checkPersonArray[i],
              initKey,
              "file",
              {
                id: this.forwarding_array.DownLoadId,
                size: this.forwarding_array.duration,
                name: this.forwarding_array.value,
                duration: this.forwarding_array.duration,
                isDownLoad: "0",
                DownLoadId: this.forwarding_array.DownLoadId,
                gender: this.checkPersonArray[i].gender || "1",
                head: this.checkPersonArray[i].head || ""
              },
              this.ws
            );
          } else if (this.forwarding_array.type == "GPS") {
            let value = JSON.parse(this.forwarding_array.value);
            value = eval("(" + value + ")");
            value = JSON.stringify(value);
            this.$wsSendMsg(
              this.checkPersonArray[i],
              initKey,
              this.forwarding_array.type,
              {
                text: value,
                gender: this.checkPersonArray[i].gender || "1",
                head: this.checkPersonArray[i].head || ""
              },
              this.ws
            );
          } else {
            this.$wsSendMsg(
              this.checkPersonArray[i],
              initKey,
              this.forwarding_array.type,
              {
                text: this.textMsg(this.forwarding_array.value),
                gender: this.checkPersonArray[i].gender || "1",
                head: this.checkPersonArray[i].head || ""
              },
              this.ws
            );
          }
          if (i == this.checkPersonArray.length - 1) this.modalFirst = false;
        }
        // this.resetContacts();
        this.resetModalFirst();
      } else if (this.modalTitle == 4) {
        for (let i = 0, len = this.checkPersonArray.length; i < len; i++) {
          arr.push({
            type: this.checkPersonArray[i].FID ? "1" : "0",
            value: this.checkPersonArray[i].id
          });
        }
        if (arr.length > 0) {
          addGroupMembers({
            userid: this.myInfo.id,
            groupid: this.toInfo.id,
            members: JSON.stringify(arr)
          }).then(res => {
            console.log(res, "添加成员");
            if (res.result == 200) {
              this.modalFirst = false;
              // this.resetContacts();
              this.$emit("getGroupAndUsers", this.toInfo.id);
              this.$Message.success("添加成员成功");
              this.resetModalFirst();
            } else {
              this.$Message.success("添加失败");
            }
          });
        } else {
          this.$Message.destroy();
          this.$Message.warning({
            content: "至少邀请一位联系人加入群",
            duration: 1
          });
        }
      }
      console.log(arr, "选择的人员对象");
    },
    //修改文本内容发送给后台
    textMsg(myMsg) {
      let regLess = /(\<div\>\<br\>\<\/div\>)*$/g; //去除末尾无意义换行
      myMsg = myMsg.replace(regLess, "");
      myMsg = myMsg;
      // console.log(myMsg)
      let reg = /\<img src=['"]static(.+?)\>/g; //匹配图片
      var imgArr = myMsg.match(reg);
      var regx = /\d+\.gif/g; //匹配gif
      var a = [];
      var sendToAndior = myMsg;
      if (imgArr) {
        for (let i = 0, len = imgArr.length; i < len; i++) {
          let sdn = imgArr[i].match(regx);
          let ins = parseInt(sdn[0].replace(".gif", "")); //获取图片数字
          // console.log(ins);
          a.push(ins);
        }
        // console.log(a)
        for (let i = 0, len = imgArr.length; i < len; i++) {
          //找到图片描述
          let m = Math.floor(a[i] / 36);
          let q = a[i] % 36;
          // console.log(m);
          // console.log(q);
          // console.log(imgArr[i]);
          sendToAndior = sendToAndior.replace(
            imgArr[i],
            "[" + this.expression[m][q] + "]"
          );
        }
      }
      //找到非<br>div
      let regAdd = /\<div\>[^\<]*\<\/div\>/g;
      let addArr = Array.from(new Set(sendToAndior.match(regAdd)));
      for (let i in addArr) {
        let arrtest = addArr[i].replace(/-/g, "/-/");
        // console.log(arrtext,'匹配字符');
        let regh = new RegExp(arrtest, "gim");
        let regDiv = /\<div\>|\<\/div\>/g;
        let str = addArr[i].replace(regDiv, "");
        sendToAndior = sendToAndior.replace(regh, str);
      }
      console.log(sendToAndior, "文本内容");
      return sendToAndior;
    }
  }
};
</script>

<style scoped lang='less'>
.homeContact {
  text-align: left;
  li {
    cursor: pointer;
    &:hover {
      background-color: #f5f6f7;
    }
    padding: 1em 1em;
    img {
      width: 4em;
      height: 4em;
      vertical-align: middle;
      margin-right: 0.8em;
    }
    span {
      font-size: 1.2em;
      font-weight: bold;
    }
    p {
      background: url(../../static/image/home/dropDown.png) no-repeat center
        center;
      width: 1em;
      height: 1em;
      display: inline-block;
    }
    &:hover p {
      background: url(../../static/image/home/dropDown_hover.png) no-repeat
        center center;
    }
    ul {
      margin-left: 2em;
      margin-top: 1em;
      li {
        font-weight: bold;
        div {
          margin-right: 0.5em;
          display: inline-block;
          width: 1em;
          height: 1em;
          background: url(../../static/image/home/contact/rectangular.png)
            no-repeat left center;
        }
      }
    }
  }
}

.homeModalSearch {
  margin-left: 0.5em;
  height: 2em;
  border: none;
  outline: none;
}

.homeModalName {
  padding-left: 1em;
  width: 100%;
  border: 1px solid #cccccc;
  border-radius: 4px;
  height: 3em;
  outline: none;
}
</style>
